package chapter

import scala.io.Source
import scala.collection.convert.WrapAsScala
import scala.collection.immutable.TreeMap

object Chapter4 extends App with WrapAsScala {

  def p(any: Any) = println(any)
  //1
  val applePriceMap = Map("iphone5s" -> 4800.0, "iphone6" -> 5200.0, "Mac_Pro" -> 12800.0)

  val discountPriceMap = for ((name, price) <- applePriceMap) yield (name, price * 0.9)

  p(applePriceMap + "\n" + discountPriceMap)

  lazy val fileLines = Source.fromFile(new java.io.File("""D:\Workspaces\Eclipse SCALA\ScalaImpatient\src\chapter4\file.txt""")).getLines.flatMap(_.split("\\s+")).toList
  //2
  val wordCounts1 = scala.collection.mutable.HashMap[String, Int]() withDefault (_ => 0)
  for (c <- fileLines) wordCounts1(c) += 1
  p(wordCounts1)

  //3
  var wordCounts2 = Map[String, Int]()
  for (c <- fileLines)
    wordCounts2 += (c -> (wordCounts2.getOrElse(c, 0) + 1))
  p(wordCounts2)

  //4 
  var wordCounts3 = scala.collection.immutable.SortedMap[String, Int]()
  for (c <- fileLines)
    wordCounts3 += (c -> (wordCounts2.getOrElse(c, 0) + 1))
  p(wordCounts3)

  //5 
  //java
  val wordCounts4 = mapAsScalaMap(new java.util.TreeMap[String, Int]())
  fileLines.foreach(key => wordCounts4(key) = wordCounts4.getOrElse(key, 0) + 1)
  //scala 
  var wordCounts5 = TreeMap.empty[String, Int]
  fileLines.foreach(key => wordCounts5 += key -> (wordCounts5.getOrElse(key, 0) + 1))
  p(wordCounts4 + "\n" + wordCounts5)

  //6
  import java.util.Calendar._
  val dateMap = collection.mutable.LinkedHashMap(
    "Monday" -> MONDAY,
    "Tuesday" -> TUESDAY,
    "Wednesday" -> WEDNESDAY,
    "Thursday" -> THURSDAY,
    "Friday" -> FRIDAY,
    "Saturday" -> SATURDAY,
    "Sunday" -> SUNDAY)
  p(dateMap)

  //7
  val props = propertiesAsScalaMap(System.getProperties())
  val maxLength = (props.keySet toList) map (_.size) max

  for ((k, v) <- props)
    p(s"""$k${" " * (maxLength - k.size)}|$v""")

  //8
  def minmax(values: Array[Int]) = (values.min, values.max)

  //9
  def lteqgt(values: Array[Int], v: Int) = {
    ((values filter (_ < v)) size, (values filter (_ == v)) size, (values filter (_ > v)) size) 
  }
  
  //10
  p("Hello".zip("World")) //Result Vector((H,W), (e,o), (l,r), (l,l), (o,d))  
  //scala �е��б��ڱ���ʱ��Ҫindex  ������zipWithIndex
}